<?php
require_once(__DIR__.'/../config.php');
require_once(__DIR__.'/../inc/ajax_guard.php');
require_once(__DIR__.'/../inc/audit_helper.php');

class Master extends DBConnection {
    private $settings;

    public function __construct(){
        global $_settings;
        $this->settings = $_settings;
        parent::__construct();
    }

    public function __destruct(){
        parent::__destruct();
    }

    /* =====================================================
       PROYECTOS – SOLO PLANEAMIENTO
       (ADMIN / SUPERVISOR / GESTOR)
       ===================================================== */

    public function save_project(){
        // ❌ PO NO puede registrar proyectos
        ajax_require_role(['ADMIN','SUPERVISOR','GESTOR']);

        $id = $_POST['id'] ?? null;
        $data = [];

        // Campos válidos en tabla projects
        $fields = [
            'project_name',
            'description',
            'leader_project',   // PO
            'leader_tech',      // Gerente/Sponsor
            'leader_it',        // Líder TI
            'commitment_period',
            'budget_total',
            'supplier'
        ];

        foreach ($fields as $f){
            if(isset($_POST[$f])){
                $v = $this->conn->real_escape_string($_POST[$f]);
                $data[] = "`$f`='$v'";
            }
        }

        /* ========== CREATE ========== */
        if(empty($id)){
            $data[] = "`approval_status` = 0"; // Registrado por Planeamiento
            $data[] = "`created_by` = ".$this->settings->userdata('id');
            $data[] = "`created_at` = NOW()";

            $sql = "INSERT INTO projects SET ".implode(", ", $data);
            $save = $this->conn->query($sql);
            $pid  = $this->conn->insert_id;

            if($save){
                audit_log(
                    'CREATE_PROJECT',
                    'project',
                    $pid,
                    'Proyecto registrado por Planeamiento'
                );
                return json_encode(['status'=>'success']);
            }

        /* ========== UPDATE ========== */
        } else {
            $sql = "UPDATE projects SET ".implode(", ", $data)." WHERE id=".(int)$id;
            $save = $this->conn->query($sql);

            if($save){
                audit_log(
                    'UPDATE_PROJECT',
                    'project',
                    (int)$id,
                    'Datos del proyecto actualizados'
                );
                return json_encode(['status'=>'success']);
            }
        }

        return json_encode([
            'status'=>'error',
            'msg'=>$this->conn->error
        ]);
    }

    /* =====================================================
       CANCELAR PROYECTO – SOLO ADMIN
       ===================================================== */

    public function delete_project(){
        ajax_require_role(['ADMIN']);

        $id = (int) $_POST['id'];

        // En PMO no se elimina: se cancela
        $this->conn->query("
            UPDATE projects
            SET approval_status = -1
            WHERE id = $id
        ");

        audit_log(
            'CANCEL_PROJECT',
            'project',
            $id,
            'Proyecto cancelado por Planeamiento'
        );

        return json_encode(['status'=>'success']);
    }

    /* =====================================================
       AVANCES MENSUALES
       PO + GESTOR
       ===================================================== */

    public function save_report(){
        // ✅ PO SÍ puede registrar avances
        ajax_require_role(['PO','GESTOR']);

        $role = $this->settings->userdata('role');
        $uid  = (int)$this->settings->userdata('id');
        $pid  = (int)$_POST['project_id'];

        // 🔐 Validación PMO: si es PO, debe ser líder del proyecto
        if($role === 'PO'){
            $check = $this->conn->query("
                SELECT id
                FROM projects
                WHERE id = $pid
                  AND leader_project = $uid
            ")->num_rows;

            if($check === 0){
                return json_encode([
                    'status'=>'error',
                    'msg'=>'No es líder del proyecto'
                ]);
            }
        }

        $_POST['employee_id'] = $uid;
        $_POST['description'] = htmlentities($_POST['description']);

        $duration = strtotime($_POST['datetime_to']) - strtotime($_POST['datetime_from']);
        $_POST['duration'] = $duration;

        $data = [];
        foreach($_POST as $k => $v){
            if($k !== 'id'){
                $v = $this->conn->real_escape_string($v);
                $data[] = "`$k`='$v'";
            }
        }

        $sql = "INSERT INTO report_list SET ".implode(",", $data);
        $save = $this->conn->query($sql);
        $rid  = $this->conn->insert_id;

        if($save){
            audit_log(
                'SAVE_REPORT',
                'report',
                $rid,
                'Avance mensual registrado'
            );
            return json_encode(['status'=>'success']);
        }

        return json_encode([
            'status'=>'error',
            'msg'=>$this->conn->error
        ]);
    }
}

/* =====================================================
   ROUTER
   ===================================================== */

$action = $_GET['f'] ?? '';
$Master = new Master();

switch($action){
    case 'save_project':
        echo $Master->save_project();
        break;

    case 'delete_project':
        echo $Master->delete_project();
        break;

    case 'save_report':
        echo $Master->save_report();
        break;

    default:
        echo json_encode([
            'status'=>'error',
            'msg'=>'Acción no válida'
        ]);
        break;
}
