<?php
class CVRevamp {
    private $conn;

    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * Submit a CV revamp request
     */
    public function submitRequest($userId, $cvFilePath, $userNotes = null) {
        $uuid = $this->generateUUID();

        $stmt = $this->conn->prepare("INSERT INTO cv_revamp_requests (uuid, user_uuid, cv_file, user_notes) VALUES (?, ?, ?, ?)");
        if (!$stmt) {
            error_log("Failed to prepare CV revamp request statement: " . $this->conn->error);
            return false;
        }
        $stmt->bind_param("ssss", $uuid, $userId, $cvFilePath, $userNotes);
        $result = $stmt->execute();

        if (!$result) {
            error_log("Failed to submit CV revamp request: " . $stmt->error);
        }

        return $result ? $uuid : false;
    }

    /**
     * Get CV revamp requests for a user
     */
    public function getUserRequests($userId) {
        $stmt = $this->conn->prepare("SELECT * FROM cv_revamp_requests WHERE user_uuid = ? ORDER BY submitted_at DESC");
        if (!$stmt) {
            return [];
        }
        $stmt->bind_param("s", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    /**
     * Get all CV revamp requests (for admin)
     */
    public function getAllRequests($filters = []) {
        $where = "";
        $params = [];
        $types = '';

        if (!empty($filters['status'])) {
            $where .= " WHERE c.status = ?";
            $params[] = $filters['status'];
            $types .= 's';
        }

        if (!empty($filters['search'])) {
            $searchTerm = '%' . $filters['search'] . '%';
            $where .= ($where ? " AND" : " WHERE") . " (js.fullName LIKE ? OR u.email LIKE ?)";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $types .= 'ss';
        }

        $limit = isset($filters['limit']) ? (int)$filters['limit'] : 30;
        $offset = isset($filters['offset']) ? (int)$filters['offset'] : 0;

        $sql = "SELECT c.*, u.email, js.fullName FROM cv_revamp_requests c
                JOIN users u ON c.user_uuid = u.uuid
                LEFT JOIN job_seekers js ON u.uuid = js.user_uuid
                $where ORDER BY c.submitted_at DESC
                LIMIT ? OFFSET ?";

        $stmt = $this->conn->prepare($sql);
        if (!$stmt) {
            return [];
        }

        $stmt->bind_param($types . 'ii', ...array_merge($params, [$limit, $offset]));

        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    /**
     * Get total count of CV revamp requests (for admin)
     */
    public function getTotalRequestsCount($filters = []) {
        $where = "";
        $params = [];
        $types = '';

        if (!empty($filters['status'])) {
            $where .= " WHERE c.status = ?";
            $params[] = $filters['status'];
            $types .= 's';
        }

        if (!empty($filters['search'])) {
            $searchTerm = '%' . $filters['search'] . '%';
            $where .= ($where ? " AND" : " WHERE") . " (js.fullName LIKE ? OR u.email LIKE ?)";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $types .= 'ss';
        }

        $sql = "SELECT COUNT(*) as total FROM cv_revamp_requests c
                JOIN users u ON c.user_uuid = u.uuid
                LEFT JOIN job_seekers js ON u.uuid = js.user_uuid
                $where";

        $stmt = $this->conn->prepare($sql);
        if (!$stmt) {
            return 0;
        }

        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }

        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        return (int)$row['total'];
    }

    /**
     * Update request status (for admin)
     */
    public function updateRequestStatus($requestId, $status, $notes = null) {
        $stmt = $this->conn->prepare("UPDATE cv_revamp_requests SET status = ?, reviewed_at = NOW(), notes = ? WHERE uuid = ?");
        if (!$stmt) {
            return false;
        }
        $stmt->bind_param("sss", $status, $notes, $requestId);
        return $stmt->execute();
    }

    /**
     * Mark request as viewed when CV is accessed
     */
    public function markAsViewed($requestId) {
        $stmt = $this->conn->prepare("UPDATE cv_revamp_requests SET status = 'viewed' WHERE uuid = ? AND status = 'pending'");
        if (!$stmt) {
            return false;
        }
        $stmt->bind_param("s", $requestId);
        return $stmt->execute();
    }

    private function generateUUID() {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
}
?>