<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') === 'guest') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int) ($_SESSION['user_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
*/
$workspace_type = $_SESSION['workspace_type'] ?? 'personal';
$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int) $_SESSION['active_company_id']
    : null;

$is_company_workspace = ($workspace_type === 'company' && $active_company_id !== null);

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

function convertToSqlDate(?string $date): ?string
{
    $date = trim((string) $date);

    if ($date === '') {
        return null;
    }

    $dt = DateTime::createFromFormat('d/m/Y', $date);
    if ($dt && $dt->format('d/m/Y') === $date) {
        return $dt->format('Y-m-d');
    }

    return null;
}

function convertToDisplayDate(?string $date): string
{
    $date = trim((string) $date);

    if ($date === '') {
        return '';
    }

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    if ($dt) {
        return $dt->format('d/m/Y');
    }

    return '';
}

function processAndSaveImage(string $tmpPath, string $destinationPath, string $extension, int $maxWidth = 1600, int $maxHeight = 1600, int $jpgQuality = 75): bool
{
    $imageInfo = getimagesize($tmpPath);
    if (!$imageInfo) {
        return false;
    }

    $mime = $imageInfo['mime'];
    $originalWidth = (int) $imageInfo[0];
    $originalHeight = (int) $imageInfo[1];

    if ($originalWidth <= 0 || $originalHeight <= 0) {
        return false;
    }

    switch ($mime) {
        case 'image/jpeg':
            $sourceImage = imagecreatefromjpeg($tmpPath);
            break;
        case 'image/png':
            $sourceImage = imagecreatefrompng($tmpPath);
            break;
        default:
            return false;
    }

    if (!$sourceImage) {
        return false;
    }

    $scale = min($maxWidth / $originalWidth, $maxHeight / $originalHeight, 1);
    $newWidth = max(1, (int) round($originalWidth * $scale));
    $newHeight = max(1, (int) round($originalHeight * $scale));

    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
    if (!$resizedImage) {
        imagedestroy($sourceImage);
        return false;
    }

    if ($mime === 'image/png') {
        imagealphablending($resizedImage, false);
        imagesavealpha($resizedImage, true);
        $transparent = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
        imagefilledrectangle($resizedImage, 0, 0, $newWidth, $newHeight, $transparent);
    }

    imagecopyresampled(
        $resizedImage,
        $sourceImage,
        0,
        0,
        0,
        0,
        $newWidth,
        $newHeight,
        $originalWidth,
        $originalHeight
    );

    $saved = false;

    if ($mime === 'image/jpeg' || in_array(strtolower($extension), ['jpg', 'jpeg'], true)) {
        $saved = imagejpeg($resizedImage, $destinationPath, $jpgQuality);
    } elseif ($mime === 'image/png' || strtolower($extension) === 'png') {
        $pngCompression = 7;
        $saved = imagepng($resizedImage, $destinationPath, $pngCompression);
    }

    imagedestroy($sourceImage);
    imagedestroy($resizedImage);

    return $saved;
}

function bindOwnership(PDOStatement $stmt, bool $is_company_workspace, ?int $active_company_id, int $user_id): void
{
    if ($is_company_workspace) {
        $stmt->bindValue(":company_id", $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(":user_id", $user_id, PDO::PARAM_INT);
    }
}

if ($id <= 0) {
    header("Location: contracts.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| Ownership logic
|--------------------------------------------------------------------------
*/
if ($is_company_workspace) {
    $ownershipSql = "id = :id AND company_id = :company_id";
} else {
    $ownershipSql = "id = :id AND user_id = :user_id AND company_id IS NULL";
}

$stmt = $db->prepare("
    SELECT *
    FROM contracts
    WHERE {$ownershipSql}
    LIMIT 1
");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
$stmt->execute();
$contract = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$contract) {
    die("Contract not found.");
}

$message = "";
$message_color = "green";

$form = [
    'customer_name' => $contract['customer_name'] ?? '',
    'contract_title' => $contract['contract_title'] ?? '',
    'contract_number' => $contract['contract_number'] ?? '',
    'start_date' => convertToDisplayDate($contract['start_date'] ?? ''),
    'expire_date' => convertToDisplayDate($contract['expire_date'] ?? ''),
    'status' => $contract['status'] ?? 'Active Customer',
    'note' => $contract['note'] ?? ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['customer_name'] = trim($_POST['customer_name'] ?? '');
    $form['contract_title'] = trim($_POST['contract_title'] ?? '');
    $form['contract_number'] = trim($_POST['contract_number'] ?? '');
    $form['start_date'] = trim($_POST['start_date'] ?? '');
    $form['expire_date'] = trim($_POST['expire_date'] ?? '');
    $form['status'] = trim($_POST['status'] ?? 'Active Customer');
    $form['note'] = trim($_POST['note'] ?? '');

    $customer_name = $form['customer_name'];
    $contract_title = $form['contract_title'];
    $contract_number = $form['contract_number'];
    $status = $form['status'];
    $note = $form['note'];

    $start_date_raw = $form['start_date'];
    $expire_date_raw = $form['expire_date'];

    $start_date = convertToSqlDate($start_date_raw);
    $expire_date = convertToSqlDate($expire_date_raw);

    if ($customer_name === '') {
        $message = "Please enter customer name.";
        $message_color = "red";
    } elseif ($contract_title === '') {
        $message = "Please enter contract title.";
        $message_color = "red";
    } elseif ($start_date_raw !== '' && $start_date === null) {
        $message = "Start date is invalid. Please use dd/mm/yyyy.";
        $message_color = "red";
    } elseif ($expire_date_raw !== '' && $expire_date === null) {
        $message = "Expire date is invalid. Please use dd/mm/yyyy.";
        $message_color = "red";
    } else {
        $new_file_name = $contract['file_name'];
        $original_file_name = $contract['original_file_name'];
        $db_file_path = $contract['file_path'];
        $file_type = $contract['file_type'];
        $file_size = $contract['file_size'];

        if (isset($_FILES['contract_file']) && $_FILES['contract_file']['error'] !== UPLOAD_ERR_NO_FILE) {
            if ($_FILES['contract_file']['error'] !== UPLOAD_ERR_OK) {
                $message = "Upload error code: " . $_FILES['contract_file']['error'];
                $message_color = "red";
            } else {
                $file = $_FILES['contract_file'];
                $upload_original_file_name = $file['name'];
                $tmp_name = $file['tmp_name'];

                $ext = strtolower(pathinfo($upload_original_file_name, PATHINFO_EXTENSION));
                $allowed = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx'];

                if (!in_array($ext, $allowed, true)) {
                    $message = "Invalid file type. Only PDF, JPG, JPEG, PNG, DOC, DOCX, XLS, XLSX allowed.";
                    $message_color = "red";
                } else {
                    $upload_dir = __DIR__ . "/uploads/";

                    if (!is_dir($upload_dir)) {
                        die("Upload folder does not exist.");
                    }

                    if (!is_writable($upload_dir)) {
                        die("Upload folder is not writable.");
                    }

                    $generated_file_name = time() . "_" . uniqid() . "." . $ext;
                    $full_file_path = $upload_dir . $generated_file_name;
                    $generated_db_file_path = "uploads/" . $generated_file_name;

                    $save_success = false;

                    if (in_array($ext, ['jpg', 'jpeg', 'png'], true)) {
                        $save_success = processAndSaveImage($tmp_name, $full_file_path, $ext, 1600, 1600, 75);

                        if (!$save_success) {
                            $save_success = move_uploaded_file($tmp_name, $full_file_path);
                        }
                    } else {
                        $save_success = move_uploaded_file($tmp_name, $full_file_path);
                    }

                    if ($save_success) {
                        if (!empty($contract['file_path'])) {
                            $old_file = __DIR__ . '/' . ltrim($contract['file_path'], '/');
                            if (file_exists($old_file) && is_file($old_file)) {
                                unlink($old_file);
                            }
                        }

                        $new_file_name = $generated_file_name;
                        $original_file_name = $upload_original_file_name;
                        $db_file_path = $generated_db_file_path;
                        $file_type = $ext;
                        $file_size = filesize($full_file_path) ?: 0;
                    } else {
                        $message = "File upload failed.";
                        $message_color = "red";
                    }
                }
            }
        }

        if ($message === "") {
            if ($is_company_workspace) {
                $stmt = $db->prepare("
                    UPDATE contracts
                    SET
                        customer_name = :customer_name,
                        contract_title = :contract_title,
                        contract_number = :contract_number,
                        start_date = :start_date,
                        expire_date = :expire_date,
                        status = :status,
                        file_name = :file_name,
                        original_file_name = :original_file_name,
                        file_path = :file_path,
                        file_type = :file_type,
                        file_size = :file_size,
                        note = :note,
                        updated_by = :updated_by
                    WHERE id = :id AND company_id = :company_id
                ");
            } else {
                $stmt = $db->prepare("
                    UPDATE contracts
                    SET
                        customer_name = :customer_name,
                        contract_title = :contract_title,
                        contract_number = :contract_number,
                        start_date = :start_date,
                        expire_date = :expire_date,
                        status = :status,
                        file_name = :file_name,
                        original_file_name = :original_file_name,
                        file_path = :file_path,
                        file_type = :file_type,
                        file_size = :file_size,
                        note = :note,
                        updated_by = :updated_by
                    WHERE id = :id AND user_id = :user_id AND company_id IS NULL
                ");
            }

            bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
            $stmt->bindValue(":updated_by", $user_id, PDO::PARAM_INT);
            $stmt->bindValue(":customer_name", $customer_name, PDO::PARAM_STR);
            $stmt->bindValue(":contract_title", $contract_title, PDO::PARAM_STR);

            if ($contract_number === '') {
                $stmt->bindValue(":contract_number", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":contract_number", $contract_number, PDO::PARAM_STR);
            }

            if ($start_date === null) {
                $stmt->bindValue(":start_date", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":start_date", $start_date, PDO::PARAM_STR);
            }

            if ($expire_date === null) {
                $stmt->bindValue(":expire_date", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":expire_date", $expire_date, PDO::PARAM_STR);
            }

            $stmt->bindValue(":status", $status, PDO::PARAM_STR);

            if ($new_file_name === null || $new_file_name === '') {
                $stmt->bindValue(":file_name", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":file_name", $new_file_name, PDO::PARAM_STR);
            }

            if ($original_file_name === null || $original_file_name === '') {
                $stmt->bindValue(":original_file_name", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":original_file_name", $original_file_name, PDO::PARAM_STR);
            }

            if ($db_file_path === null || $db_file_path === '') {
                $stmt->bindValue(":file_path", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":file_path", $db_file_path, PDO::PARAM_STR);
            }

            if ($file_type === null || $file_type === '') {
                $stmt->bindValue(":file_type", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":file_type", $file_type, PDO::PARAM_STR);
            }

            $stmt->bindValue(":file_size", (int) $file_size, PDO::PARAM_INT);

            if ($note === '') {
                $stmt->bindValue(":note", null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(":note", $note, PDO::PARAM_STR);
            }

            $stmt->bindValue(":id", $id, PDO::PARAM_INT);

            if ($stmt->execute()) {
                $message = "Contract updated successfully.";
                $message_color = "green";

                $stmtReload = $db->prepare("
                    SELECT *
                    FROM contracts
                    WHERE {$ownershipSql}
                    LIMIT 1
                ");
                $stmtReload->bindValue(":id", $id, PDO::PARAM_INT);
                bindOwnership($stmtReload, $is_company_workspace, $active_company_id, $user_id);
                $stmtReload->execute();
                $contract = $stmtReload->fetch(PDO::FETCH_ASSOC);

                $form = [
                    'customer_name' => $contract['customer_name'] ?? '',
                    'contract_title' => $contract['contract_title'] ?? '',
                    'contract_number' => $contract['contract_number'] ?? '',
                    'start_date' => convertToDisplayDate($contract['start_date'] ?? ''),
                    'expire_date' => convertToDisplayDate($contract['expire_date'] ?? ''),
                    'status' => $contract['status'] ?? 'Active Customer',
                    'note' => $contract['note'] ?? ''
                ];
            } else {
                $message = "Update failed.";
                $message_color = "red";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Contract</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <style>
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 18px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #344054;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #d0d5dd;
            border-radius: 12px;
            font-size: 14px;
            background: #fff;
            box-sizing: border-box;
        }

        .form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .hint {
            color: #667085;
            font-size: 13px;
            margin-top: 6px;
        }

        .alert-box {
            padding: 14px 16px;
            border-radius: 14px;
            margin-bottom: 18px;
            font-weight: 600;
        }

        .alert-success {
            background: #ecfdf3;
            color: #027a48;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
        }

        .page-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 18px;
        }

        .current-file {
            margin-top: 8px;
            font-size: 14px;
            color: #475467;
        }

        .current-file a {
            color: #175cd3;
            text-decoration: none;
        }

        .workspace-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #eff8ff;
            color: #175cd3;
            border: 1px solid #b2ddff;
            margin-top: 12px;
        }
    </style>
</head>
<body>
<div class="layout">

    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Edit Contract</h1>
                    <p>Update contract details and replace the file if needed.</p>
                    <div class="workspace-badge">
                        Viewing: <?php echo $is_company_workspace ? 'Company Workspace' : 'Personal Workspace'; ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <?php if ($message !== ''): ?>
            <div class="alert-box <?php echo $message_color === 'green' ? 'alert-success' : 'alert-danger'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="section-title">Edit Contract</div>
            <div class="section-subtext">Update the fields below.</div>

            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="customer_name">Customer Name</label>
                        <input type="text" name="customer_name" id="customer_name" value="<?php echo htmlspecialchars($form['customer_name']); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="contract_title">Contract Title</label>
                        <input type="text" name="contract_title" id="contract_title" value="<?php echo htmlspecialchars($form['contract_title']); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="contract_number">Contract Number</label>
                        <input type="text" name="contract_number" id="contract_number" value="<?php echo htmlspecialchars($form['contract_number']); ?>">
                    </div>

                    <div class="form-group">
                        <label for="start_date">Start Date</label>
                        <input type="text" name="start_date" id="start_date" value="<?php echo htmlspecialchars($form['start_date']); ?>" placeholder="dd/mm/yyyy">
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="expire_date">Expire Date</label>
                        <input type="text" name="expire_date" id="expire_date" value="<?php echo htmlspecialchars($form['expire_date']); ?>" placeholder="dd/mm/yyyy">
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="status">Status</label>
                        <select name="status" id="status">
                            <option value="Active Customer" <?php echo ($form['status'] === 'Active Customer') ? 'selected' : ''; ?>>Active Customer</option>
                            <option value="Pending" <?php echo ($form['status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="Expired" <?php echo ($form['status'] === 'Expired') ? 'selected' : ''; ?>>Expired</option>
                            <option value="Cancelled" <?php echo ($form['status'] === 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>

                    <div class="form-group full">
                        <label for="note">Note</label>
                        <textarea name="note" id="note"><?php echo htmlspecialchars($form['note']); ?></textarea>
                    </div>

                    <div class="form-group full">
                        <label for="contract_file">Replace File (optional)</label>
                        <input type="file" name="contract_file" id="contract_file">
                        <?php if (!empty($contract['file_path'])): ?>
                            <div class="current-file">
                                Current file:
                                <a href="<?php echo htmlspecialchars($contract['file_path']); ?>" target="_blank">
                                    <?php echo htmlspecialchars($contract['original_file_name'] ?? 'View file'); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="page-actions">
                    <button type="submit" class="btn btn-primary">Update Contract</button>
                    <a href="contracts.php" class="btn btn-secondary">Contracts</a>
                    <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
                </div>
            </form>
        </div>
    </main>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    flatpickr("#start_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });

    flatpickr("#expire_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });
});
</script>
</body>
</html>