<?php
// format_crud.php - Handles add, edit, delete for formats table

// DEBUG: Show all errors for troubleshooting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
header('Content-Type: application/json');
$pdo = require __DIR__ . '/../config/db.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'error' => 'Database connection failed. $pdo is not a PDO object.'
    ]);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
    exit;
}

$action = $_POST['action'] ?? '';
$fields = [
    'supplier', 'type', 'format', 'size_x_m', 'size_y_m', 'size_x_p', 'size_y_y',
    'image_base', 'pdooh', 'market', 'district', 'ward', 'street', 'street_no',
    'format_coordination', 'supplier_cost', 'duration', 'duration_buy', 'discount',
    'availability', 'current_own', 'image_comp', 'plan_cost', 'buy_type', 'evaluate_score',
    'buy_cost', 'profit_lost'
];

$numericFields = [
    'size_x_m','size_y_m','size_x_p','size_y_y',
    'supplier_cost','plan_cost','buy_cost','discount','evaluate_score','profit_lost'
];
$data = [];
foreach ($fields as $f) {
    $val = isset($_POST[$f]) ? trim($_POST[$f]) : null;
    if ($val === '') $val = null;
    if (in_array($f, $numericFields) && $val !== null) {
        // Remove commas and percent signs, then cast
        $val = str_replace([',','%',' VND'], '', $val);
        if ($f === 'discount' || $f === 'profit_lost' || $f === 'evaluate_score') {
            $val = is_numeric($val) ? floatval($val) : null;
        } else {
            $val = is_numeric($val) ? intval($val) : null;
        }
    }
    $data[$f] = $val;
}

if ($action === 'get') {
    $id = $_POST['format_id'] ?? $_POST['id'] ?? null;
    if (!$id) {
        echo json_encode(['success' => false, 'error' => 'Missing format ID.']);
        exit;
    }
    $stmt = $pdo->prepare('SELECT * FROM sites WHERE id = ?');
    if ($stmt->execute([$id])) {
        $format = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($format) {
            echo json_encode(['success' => true, 'format' => $format]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Format not found.']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Database error.']);
    }
    exit;
}

/// ADDING NEW FORMAT /////////////////////
if ($action === 'add') {
    $required = ['supplier', 'type', 'format'];
    foreach ($required as $r) {
        if (empty($data[$r])) {
            echo json_encode(['success' => false, 'error' => 'Missing required field: ' . $r]);
            exit;
        }
    }
    // Patch: If image_base or image_comp is empty, try to find the latest uploaded tmp image for this session

    if (empty($data['image_base'])) {
        $tmpDir = dirname(__DIR__) . '/media/tmp/';
        if (is_dir($tmpDir)) {
            $files = glob($tmpDir . session_id() . '_*');
            if ($files) {
                // Get the most recent file
                usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });
                $latest = basename($files[0]);
                $data['image_base'] = 'tmp/' . $latest;
            }
        }
    }
    
    $sql = "INSERT INTO sites (
        supplier, type, format, size_x_m, size_y_m, size_x_p, size_y_y,
        image_base, pdooh, market, district, ward, street, street_no,
        format_coordination, supplier_cost, duration, duration_buy, discount,
        availability, current_own, image_comp, plan_cost, buy_type, evaluate_score,
        buy_cost, profit_lost
    ) VALUES (
        ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
    )";
    $params = array_values($data);
    $stmt = $pdo->prepare($sql);
    if (!$stmt->execute($params)) {
        echo json_encode(['success' => false, 'error' => 'Insert failed.']);
        exit;
    }
    $newId = $pdo->lastInsertId();
    // If image_base or image_comp is a temp file, move it to /media/ and update DB
    if (!empty($data['image_base']) && strpos($data['image_base'], 'tmp/') === 0) {
        $mediaDir = dirname(__DIR__) . '/media/';
        $tmpPath = $mediaDir . $data['image_base'];
        $tmpBase = basename($data['image_base']);
        $parts = explode('_', $tmpBase, 3); // session_id, time, original name
        if (count($parts) === 3) {
            $finalName = $parts[1] . '_' . $parts[2]; // time + original name
        } else {
            $finalName = time() . '_' . $tmpBase; // fallback
        }
        $finalPath = $mediaDir . $finalName;
        if (file_exists($tmpPath) && rename($tmpPath, $finalPath)) {
            $stmt2 = $pdo->prepare("UPDATE sites SET image_base = ? WHERE id = ?");
            $stmt2->execute([$finalName, $newId]);
            // Clean up all tmp files for this session after successful move
            $tmpDir = $mediaDir . 'tmp/';
            if (is_dir($tmpDir)) {
                $sessionFiles = glob($tmpDir . session_id() . '_*');
                foreach ($sessionFiles as $sf) {
                    if (is_file($sf)) {
                        @unlink($sf);
                    }
                }
            }
        }
    }
    
    echo json_encode(['success' => true]);
    exit;
}

/// EDIT & UPDATE CURRENT FORMAT /////////////////////
if ($action === 'edit') {
    $id = $_POST['format_id'] ?? $_POST['id'] ?? null;
    if (!$id) {
        echo json_encode(['success' => false, 'error' => 'Missing format ID.']);
        exit;
    }
    $updateData = [];
    foreach ($fields as $element) {
        if (array_key_exists($element, $_POST) && $data[$element] !== null) {
            $updateData[] = $data[$element];
        }
    }
    if (empty($updateData)) {
        echo json_encode(['success' => false, 'error' => 'No fields to update.']);
        exit;
    }
    $sql = "UPDATE sites SET " . implode(',', $updateData) . " WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    echo json_encode(['success' => true]);
    exit;
}

/// DELETE CURRENT FORMAT /////////////////////
if ($action === 'delete') {
    $id = $_POST['format_id'] ?? $_POST['id'] ?? null;
    if (!$id) {
        echo json_encode(['success' => false, 'error' => 'Missing format ID.']);
        exit;
    }
    $sql = "DELETE FROM sites WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    if (!$stmt->execute([$id])) {
        echo json_encode(['success' => false, 'error' => 'Delete failed.']);
        exit;
    }
    echo json_encode(['success' => true]);
    exit;
}

// If we reach here, something went wrong. Output all POST and error info for debugging
$debug = [
    'success' => false,
    'error' => 'Unknown action.',
    'post' => $_POST,
    'fields' => $fields,
    'data' => $data,
];
if (function_exists('error_get_last')) {
    $debug['php_error'] = error_get_last();
}
echo json_encode($debug);
