<?php

class ApiprojectsController extends Controller {

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('ProjectList','ConnectToProject'),
                'users' => array('*'),
            ),
        );
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

public function actionProjectList()
{
    /* Fetch active projects */
    $projects = Projects::model()->findAll([
        'condition' => 'isActive = "Y"',
        'order' => 'project_name ASC'
    ]);

    if (empty($projects)) {
        echo json_encode([
            'status' => 'failed',
            'message' => 'No projects found'
        ]);
        Yii::app()->end();
    }

    $projectList = [];

    foreach ($projects as $project) {
        $projectList[] = [
            'project_id'   => $project->id,
            'project_name' => $project->project_name
        ];
    }

    echo json_encode([
        'status' => 'success',
        'projects' => $projectList
    ]);

    Yii::app()->end();
}



public function actionConnectToProject_old()
{
    $input = json_decode(file_get_contents('php://input'), true);

    $projectId = $input['project_id'] ?? null;
    $userId    = $input['user_id'] ?? null;
    $remotePath = $input['remote_path'] ?? '/';

    if (empty($projectId) || empty($userId)) {
        echo CJSON::encode([
            'status' => 'failed',
            'message' => 'Project ID and User ID are required'
        ]);
        Yii::app()->end();
    }

    try {

        /* ===============================
           STEP 1: Log project access
           =============================== */
        $log = new LogProjects();
        $log->project_id     = $projectId;
        $log->user_id        = $userId;
        $log->view_date_time = new CDbExpression('NOW()');
        $log->save(false);

        /* ===============================
           STEP 2: Fetch active project
           =============================== */
        $project = Projects::model()->find([
            'condition' => 'id = :id AND isActive = "Y"',
            'params'    => [':id' => $projectId]
        ]);

        if (!$project) {
            echo CJSON::encode([
                'status' => 'failed',
                'message' => 'Project not found or inactive'
            ]);
            Yii::app()->end();
        }

        /* ===============================
           STEP 3: FTP connection
           =============================== */
        $ftpPort = !empty($project->ftp_port) ? $project->ftp_port : 21;

        $ftpConn = @ftp_connect($project->ftp_address, $ftpPort, 30);
        if (!$ftpConn) {
            echo CJSON::encode([
                'status' => 'failed',
                'message' => 'Could not connect to FTP server'
            ]);
            Yii::app()->end();
        }

        if (!@ftp_login($ftpConn, $project->ftp_username, $project->ftp_password)) {
            ftp_close($ftpConn);
            echo CJSON::encode([
                'status' => 'failed',
                'message' => 'FTP login failed'
            ]);
            Yii::app()->end();
        }

        ftp_pasv($ftpConn, true);

        /* ===============================
           STEP 4: Store FTP session
           =============================== */
        $sessionId = session_id() . '_' . $projectId . '_' . time();

        $ftpModel = FtpConnections::model()->findByAttributes([
            'session_id' => $sessionId
        ]);

        if (!$ftpModel) {
            $ftpModel = new FtpConnections();
            $ftpModel->session_id = $sessionId;
        }

        $ftpModel->user_id  = $userId;
        $ftpModel->host     = $project->ftp_address;
        $ftpModel->port     = $ftpPort;
        $ftpModel->username = $project->ftp_username;
        $ftpModel->password = $project->ftp_password;
        $ftpModel->last_active = new CDbExpression('NOW()');
        $ftpModel->save(false);

        /* ===============================
           STEP 5: List FTP files
           =============================== */
        $list = @ftp_rawlist($ftpConn, $remotePath);
        ftp_close($ftpConn);

        if ($list === false) {
            echo CJSON::encode([
                'status' => 'failed',
                'message' => 'Failed to list directory'
            ]);
            Yii::app()->end();
        }

        $files = [];
        foreach ($list as $item) {
            $parsed = parseFtpRawList($item);
            $files[] = [
                'name'         => $parsed['name'],
                'size'         => $parsed['size'],
                'type'         => $parsed['type'],
                'modifiedAt'   => $parsed['modifiedAt'],
                'permissions'  => $parsed['permissions']
            ];
        }

        /* ===============================
           SUCCESS RESPONSE
           =============================== */
        echo CJSON::encode([
            'status'    => 'success',
            'message'   => 'Connected successfully',
            'sessionId' => $sessionId,
            'data' => [
                'project_id' => $projectId,
                'path'       => $remotePath,
                'files'      => $files
            ]
        ]);

    } catch (Exception $e) {
        echo CJSON::encode([
            'status' => 'failed',
            'message' => 'Server error: ' . $e->getMessage()
        ]);
    }

    Yii::app()->end();
}


public function actionConnectToProject()
{
    $input = json_decode(file_get_contents('php://input'), true);

    $projectId  = $input['project_id'] ?? '';
    $userId     = $input['user_id'] ?? '';
    $remotePath = $input['remote_path'] ?? '/';

    if (empty($projectId) || empty($userId)) {
        echo CJSON::encode([
            'status'  => 'failed',
            'message' => 'Project ID and User ID are required'
        ]);
        Yii::app()->end();
    }

    try {
        $db = Yii::app()->db;

        // ===============================
        // Step 1: Insert log_projects
        // ===============================
        $db->createCommand("
            INSERT INTO crm_log_projects (project_id, user_id, view_date_time)
            VALUES (:project_id, :user_id, NOW())
        ")->execute([
            ':project_id' => $projectId,
            ':user_id'    => $userId
        ]);

        // ===============================
        // Step 2: Fetch project FTP details
        // ===============================
        $project = $db->createCommand("
            SELECT id, ftp_address, ftp_username, ftp_password, ftp_port
            FROM crm_projects
            WHERE id = :project_id AND isActive = 'Y'
            LIMIT 1
        ")->queryRow(true, [
            ':project_id' => $projectId
        ]);

        if (!$project) {
            echo CJSON::encode([
                'status'  => 'failed',
                'message' => 'Project not found or inactive'
            ]);
            Yii::app()->end();
        }

        // ===============================
        // Step 3: FTP connect
        // ===============================
        $ftpPort = !empty($project['ftp_port']) ? $project['ftp_port'] : 21;

        $ftpConn = @ftp_connect($project['ftp_address'], $ftpPort, 30);
        if (!$ftpConn) {
            echo CJSON::encode([
                'status'  => 'failed',
                'message' => 'Could not connect to FTP server'
            ]);
            Yii::app()->end();
        }

        if (!@ftp_login($ftpConn, $project['ftp_username'], $project['ftp_password'])) {
            ftp_close($ftpConn);
            echo CJSON::encode([
                'status'  => 'failed',
                'message' => 'FTP login failed'
            ]);
            Yii::app()->end();
        }

        ftp_pasv($ftpConn, true);

        // ===============================
        // Step 4: Save FTP connection
        // ===============================
        $sessionId = session_id() . '_' . $projectId . '_' . time();

        $db->createCommand("
            INSERT INTO crm_ftp_connections
                (session_id, user_id, host, port, username, password)
            VALUES
                (:session_id, :user_id, :host, :port, :username, :password)
            ON DUPLICATE KEY UPDATE
                host = :host,
                port = :port,
                username = :username,
                password = :password,
                user_id = :user_id,
                last_active = CURRENT_TIMESTAMP
        ")->execute([
            ':session_id' => $sessionId,
            ':user_id'    => $userId,
            ':host'       => $project['ftp_address'],
            ':port'       => $ftpPort,
            ':username'   => $project['ftp_username'],
            ':password'   => $project['ftp_password']
        ]);

        // ===============================
        // Step 5: List directory
        // ===============================
        $list = @ftp_rawlist($ftpConn, $remotePath);
        ftp_close($ftpConn);

        if ($list === false) {
            echo CJSON::encode([
                'status'  => 'failed',
                'message' => 'Failed to list directory'
            ]);
            Yii::app()->end();
        }

        $files = [];
        foreach ($list as $item) {
            $parsed = parseFtpRawList($item);
            $files[] = [
                'name'        => $parsed['name'],
                'size'        => $parsed['size'],
                'type'        => $parsed['type'],
                'modifiedAt'  => $parsed['modifiedAt'],
                'permissions' => $parsed['permissions']
            ];
        }

        // ===============================
        // Success response
        // ===============================
        echo CJSON::encode([
            'status'    => 'success',
            'message'   => 'Connected successfully',
            'sessionId' => $sessionId,
            'data' => [
                'project_id' => $projectId,
                'path'       => $remotePath,
                'files'      => $files
            ]
        ]);

        Yii::app()->end();

    } catch (Exception $e) {
        echo CJSON::encode([
            'status'  => 'failed',
            'message' => $e->getMessage()
        ]);
        Yii::app()->end();
    }
}





}
