<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

if (!isset($_SESSION['user_id']) || !in_array((string)($_SESSION['user_role'] ?? ''), ['admin', 'staff'], true)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$connection->query("
    CREATE TABLE IF NOT EXISTS projects (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        category VARCHAR(100) NOT NULL DEFAULT 'Interior',
        location VARCHAR(120) NOT NULL DEFAULT '',
        project_year VARCHAR(10) NOT NULL DEFAULT '',
        image VARCHAR(500) NOT NULL DEFAULT '',
        description TEXT,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_sort_order (sort_order),
        INDEX idx_is_active (is_active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$action = trim((string)($_POST['action'] ?? ''));

function uploadProjectImage(array $file): array
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => 'Image upload error'];
    }

    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $mimeType = (string)($file['type'] ?? '');
    if (!in_array($mimeType, $allowedTypes, true)) {
        return ['success' => false, 'message' => 'Invalid image type'];
    }

    $size = (int)($file['size'] ?? 0);
    if ($size <= 0 || $size > 5 * 1024 * 1024) {
        return ['success' => false, 'message' => 'Image size must be <= 5MB'];
    }

    $ext = strtolower((string)pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));
    if ($ext === '') {
        $ext = 'jpg';
    }

    $uploadDir = __DIR__ . '/../assets/img/project/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $filename = 'project_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $targetPath = $uploadDir . $filename;
    if (!move_uploaded_file((string)$file['tmp_name'], $targetPath)) {
        return ['success' => false, 'message' => 'Failed to save uploaded image'];
    }

    return ['success' => true, 'path' => 'assets/img/project/' . $filename];
}

try {
    if ($action === 'add') {
        $title = trim((string)($_POST['title'] ?? ''));
        $category = trim((string)($_POST['category'] ?? 'Interior'));
        $location = trim((string)($_POST['location'] ?? ''));
        $projectYear = trim((string)($_POST['project_year'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 1);

        if ($title === '' || $category === '') {
            throw new RuntimeException('Title and category are required');
        }

        if (!isset($_FILES['image']) || (int)($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            throw new RuntimeException('Project image is required');
        }

        $upload = uploadProjectImage($_FILES['image']);
        if (!$upload['success']) {
            throw new RuntimeException((string)$upload['message']);
        }
        $imagePath = (string)$upload['path'];

        $stmt = $connection->prepare("
            INSERT INTO projects (title, category, location, project_year, image, description, sort_order, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        if (!$stmt) {
            throw new RuntimeException('Failed to prepare insert');
        }
        $stmt->bind_param('ssssssii', $title, $category, $location, $projectYear, $imagePath, $description, $sortOrder, $isActive);
        $stmt->execute();
        $stmt->close();

        echo json_encode(['success' => true, 'message' => 'Project added successfully']);
        exit;
    }

    if ($action === 'update') {
        $projectId = (int)($_POST['project_id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $category = trim((string)($_POST['category'] ?? 'Interior'));
        $location = trim((string)($_POST['location'] ?? ''));
        $projectYear = trim((string)($_POST['project_year'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 1);

        if ($projectId <= 0 || $title === '' || $category === '') {
            throw new RuntimeException('Invalid project data');
        }

        $currentImage = '';
        $findStmt = $connection->prepare("SELECT image FROM projects WHERE id = ?");
        if (!$findStmt) {
            throw new RuntimeException('Failed to prepare select');
        }
        $findStmt->bind_param('i', $projectId);
        $findStmt->execute();
        $findResult = $findStmt->get_result();
        if (!$findResult || !$findResult->num_rows) {
            $findStmt->close();
            throw new RuntimeException('Project not found');
        }
        $current = $findResult->fetch_assoc();
        $currentImage = (string)($current['image'] ?? '');
        $findStmt->close();

        $newImage = $currentImage;
        if (isset($_FILES['image']) && (int)($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
            $upload = uploadProjectImage($_FILES['image']);
            if (!$upload['success']) {
                throw new RuntimeException((string)$upload['message']);
            }
            $newImage = (string)$upload['path'];

            $oldPath = __DIR__ . '/../' . ltrim($currentImage, '/');
            if ($currentImage !== '' && strpos($currentImage, 'assets/img/project/') === 0 && file_exists($oldPath)) {
                @unlink($oldPath);
            }
        }

        $stmt = $connection->prepare("
            UPDATE projects
            SET title = ?, category = ?, location = ?, project_year = ?, image = ?, description = ?, sort_order = ?, is_active = ?
            WHERE id = ?
        ");
        if (!$stmt) {
            throw new RuntimeException('Failed to prepare update');
        }
        $stmt->bind_param('ssssssiii', $title, $category, $location, $projectYear, $newImage, $description, $sortOrder, $isActive, $projectId);
        $stmt->execute();
        $stmt->close();

        echo json_encode(['success' => true, 'message' => 'Project updated successfully']);
        exit;
    }

    if ($action === 'delete') {
        $projectId = (int)($_POST['project_id'] ?? 0);
        if ($projectId <= 0) {
            throw new RuntimeException('Invalid project id');
        }

        $imagePath = '';
        $findStmt = $connection->prepare("SELECT image FROM projects WHERE id = ?");
        if (!$findStmt) {
            throw new RuntimeException('Failed to prepare select');
        }
        $findStmt->bind_param('i', $projectId);
        $findStmt->execute();
        $findResult = $findStmt->get_result();
        if ($findResult && $findResult->num_rows) {
            $row = $findResult->fetch_assoc();
            $imagePath = (string)($row['image'] ?? '');
        }
        $findStmt->close();

        $deleteStmt = $connection->prepare("DELETE FROM projects WHERE id = ?");
        if (!$deleteStmt) {
            throw new RuntimeException('Failed to prepare delete');
        }
        $deleteStmt->bind_param('i', $projectId);
        $deleteStmt->execute();
        $affected = $deleteStmt->affected_rows;
        $deleteStmt->close();

        if ($affected <= 0) {
            throw new RuntimeException('Project not found');
        }

        $oldPath = __DIR__ . '/../' . ltrim($imagePath, '/');
        if ($imagePath !== '' && strpos($imagePath, 'assets/img/project/') === 0 && file_exists($oldPath)) {
            @unlink($oldPath);
        }

        echo json_encode(['success' => true, 'message' => 'Project deleted successfully']);
        exit;
    }

    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
