<?php
ob_start();
header('Content-Type: application/json; charset=utf-8');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    session_start();
    
    // Inicialización centralizada
    require_once __DIR__ . '/../core/api.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    
    $pdo->exec("SET NAMES 'utf8mb4'");

    $userId = $_SESSION['user_id'] ?? null;
    if (!$userId) throw new Exception('ACCESO NO AUTORIZADO');

    $data = $_POST;

    if (empty($data['name']) || empty($data['client_id']) || empty($data['service_id']) || empty($data['start_date'])) {
        throw new Exception('DATOS OBLIGATORIOS FALTANTES');
    }

    $name = trim($data['name']);
    $client_id = filter_var($data['client_id'], FILTER_VALIDATE_INT);
    $service_id = filter_var($data['service_id'], FILTER_VALIDATE_INT);
    $start_date = $data['start_date'];
    $due_date = !empty($data['due_date']) ? $data['due_date'] : null;
    $description = trim($data['description'] ?? '');
    $status = 'Aprobado';

    // --- VERIFICAR CLIENTE ---
    $stmt_check = $pdo->prepare("SELECT COUNT(*) as client_ok FROM clients WHERE id = ? AND user_id = ?");
    $stmt_check->execute([$client_id, $userId]);
    $check_result = $stmt_check->fetch(PDO::FETCH_ASSOC);

    if ($check_result['client_ok'] == 0) {
         throw new Exception('CLIENTE NO VÁLIDO O NO TE PERTENECE');
    }

    // Insertar
    $sql = "INSERT INTO projects (name, client_id, service_id, start_date, due_date, description, status) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$name, $client_id, $service_id, $start_date, $due_date, $description, $status]);
    
    $new_project_id = $pdo->lastInsertId();

    // Recuperar datos
    $stmt_get = $pdo->prepare("
        SELECT p.id, p.name, p.description, p.start_date, p.due_date, p.status, p.updated_at, 
               c.first_name, c.last_name, p.client_id, 
               s.name as service_name, s.id as service_id
        FROM projects p
        JOIN clients c ON p.client_id = c.id
        LEFT JOIN services s ON p.service_id = s.id
        WHERE p.id = ?
    ");
    $stmt_get->execute([$new_project_id]);
    $new_project = $stmt_get->fetch(PDO::FETCH_ASSOC);

    if ($new_project) {
        $new_project['client_name'] = trim(($new_project['first_name']??'') . ' ' . ($new_project['last_name']??''));
        $new_project['name'] = htmlspecialchars($new_project['name'], ENT_QUOTES, 'UTF-8');
        $new_project['description'] = htmlspecialchars($new_project['description']??'', ENT_QUOTES, 'UTF-8');
        
        $response = ['success' => true, 'message' => 'PROYECTO CREADO', 'project' => $new_project];
    }

} catch (PDOException $e) {
    error_log("Error PDO Create: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR AL GUARDAR: ' . $e->getMessage()];
} catch (Exception $e) {
    $response = ['success' => false, 'message' => $e->getMessage()];
}

if (ob_get_level() > 0) ob_end_clean();
echo json_encode($response);
exit;
?>