<?php
require_once '../db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add_client':
                $name = trim($_POST['name']);
                $email = trim($_POST['email']);
                $company = trim($_POST['company']);
                $code = trim($_POST['code']);
                
                if (empty($name) || empty($email) || empty($code)) {
                    throw new Exception('Required fields are missing');
                }
                
                if (!preg_match('/^[0-9]{8}$/', $code)) {
                    throw new Exception('Access code must be 8 digits');
                }
                
                $checkCode = $pdo->prepare("SELECT id FROM users WHERE code = ?");
                $checkCode->execute([$code]);
                if ($checkCode->fetch()) {
                    throw new Exception('Access code already exists');
                }
                
                $stmt = $pdo->prepare("INSERT INTO users (name, email, company, code) VALUES (?, ?, ?, ?)");
                $stmt->execute([$name, $email, $company ?: null, $code]);
                
                header('Location: index.php?success=client_added');
                exit();
                
            case 'add_project':
                $userId = (int)$_POST['user_id'];
                $projectName = trim($_POST['project_name']);
                $description = trim($_POST['description']);
                $domainName = trim($_POST['domain_name']);
                $visitLink = trim($_POST['visit_link']);
                $status = $_POST['status'];
                
                if (empty($userId) || empty($projectName)) {
                    throw new Exception('User and project name are required');
                }
                
                $stmt = $pdo->prepare("INSERT INTO projects (user_id, project_name, description, domain_name, visit_link, status) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $userId, 
                    $projectName, 
                    $description ?: null, 
                    $domainName ?: null, 
                    $visitLink ?: null, 
                    $status
                ]);
                
                $projectId = $pdo->lastInsertId();
                
                $logStmt = $pdo->prepare("INSERT INTO project_logs (project_id, log_type, title, description, new_status, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                $logStmt->execute([
                    $projectId,
                    'status_change',
                    'Project Created',
                    'Project has been created and added to the system',
                    $status,
                    'AktasCorp Admin'
                ]);
                
                header('Location: index.php?success=project_added');
                exit();
                
            case 'add_request':
                $userId = (int)$_POST['user_id'];
                $projectId = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
                $subject = trim($_POST['subject']);
                $message = trim($_POST['message']);
                $priority = $_POST['priority'];
                $status = $_POST['status'];
                
                if (empty($userId) || empty($subject) || empty($message)) {
                    throw new Exception('User, subject and message are required');
                }
                
                $stmt = $pdo->prepare("INSERT INTO requests (user_id, project_id, subject, message, priority, status) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$userId, $projectId, $subject, $message, $priority, $status]);
                
                header('Location: index.php?success=request_added');
                exit();
                
            case 'add_log':
                $projectId = (int)$_POST['project_id'];
                $logType = $_POST['log_type'];
                $title = trim($_POST['title']);
                $description = trim($_POST['description']);
                $createdBy = trim($_POST['created_by']);
                
                if (empty($projectId) || empty($title)) {
                    throw new Exception('Project ID and title are required');
                }
                
                $stmt = $pdo->prepare("INSERT INTO project_logs (project_id, log_type, title, description, created_by) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$projectId, $logType, $title, $description ?: null, $createdBy]);
                
                header('Location: index.php?success=log_added');
                exit();
                
            case 'respond_request':
                $requestId = (int)$_POST['request_id'];
                $message = trim($_POST['message']);
                $newStatus = $_POST['new_status'];
                $responderName = trim($_POST['responder_name']);
                
                if (empty($requestId) || empty($message)) {
                    throw new Exception('Request ID and message are required');
                }
                
                $pdo->beginTransaction();
                
                $responseStmt = $pdo->prepare("INSERT INTO responses (request_id, responder_name, message, is_admin_response) VALUES (?, ?, ?, ?)");
                $responseStmt->execute([$requestId, $responderName, $message, true]);
                
                if (!empty($newStatus)) {
                    $updateStmt = $pdo->prepare("UPDATE requests SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    $updateStmt->execute([$newStatus, $requestId]);
                }
                
                $pdo->commit();
                
                header('Location: index.php?success=response_sent');
                exit();
                
            case 'update_project_status':
                $projectId = (int)$_POST['project_id'];
                $newStatus = $_POST['new_status'];
                $logTitle = $_POST['log_title'];
                $logDescription = $_POST['log_description'];
                
                if (empty($projectId) || empty($newStatus)) {
                    throw new Exception('Project ID and new status are required');
                }
                
                $pdo->beginTransaction();
                
                $getOldStatus = $pdo->prepare("SELECT status FROM projects WHERE id = ?");
                $getOldStatus->execute([$projectId]);
                $oldStatus = $getOldStatus->fetchColumn();
                
                $updateStmt = $pdo->prepare("UPDATE projects SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $updateStmt->execute([$newStatus, $projectId]);
                
                $logStmt = $pdo->prepare("INSERT INTO project_logs (project_id, log_type, title, description, old_status, new_status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $logStmt->execute([
                    $projectId,
                    'status_change',
                    $logTitle ?: 'Status Updated',
                    $logDescription ?: 'Project status changed via admin panel',
                    $oldStatus,
                    $newStatus,
                    'AktasCorp Admin'
                ]);
                
                $pdo->commit();
                
                header('Location: index.php?success=status_updated');
                exit();
                
            case 'update_request_status':
                $requestId = (int)$_POST['request_id'];
                $newStatus = $_POST['new_status'];
                
                if (empty($requestId) || empty($newStatus)) {
                    throw new Exception('Request ID and new status are required');
                }
                
                $stmt = $pdo->prepare("UPDATE requests SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$newStatus, $requestId]);
                
                header('Location: index.php?success=request_updated');
                exit();
                
            case 'edit_client':
                $clientId = (int)$_POST['client_id'];
                $name = trim($_POST['name']);
                $email = trim($_POST['email']);
                $company = trim($_POST['company']);
                $code = trim($_POST['code']);
                
                if (empty($clientId) || empty($name) || empty($email) || empty($code)) {
                    throw new Exception('Required fields are missing');
                }
                
                if (!preg_match('/^[0-9]{8}$/', $code)) {
                    throw new Exception('Access code must be 8 digits');
                }
                
                $checkCode = $pdo->prepare("SELECT id FROM users WHERE code = ? AND id != ?");
                $checkCode->execute([$code, $clientId]);
                if ($checkCode->fetch()) {
                    throw new Exception('Access code already exists');
                }
                
                $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, company = ?, code = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$name, $email, $company ?: null, $code, $clientId]);
                
                header('Location: index.php?success=client_updated');
                exit();
                
            case 'edit_project':
                $projectId = (int)$_POST['project_id'];
                $projectName = trim($_POST['project_name']);
                $description = trim($_POST['description']);
                $domainName = trim($_POST['domain_name']);
                $visitLink = trim($_POST['visit_link']);
                $status = $_POST['status'];
                
                if (empty($projectId) || empty($projectName)) {
                    throw new Exception('Project ID and name are required');
                }
                
                $stmt = $pdo->prepare("UPDATE projects SET project_name = ?, description = ?, domain_name = ?, visit_link = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([
                    $projectName, 
                    $description ?: null, 
                    $domainName ?: null, 
                    $visitLink ?: null, 
                    $status, 
                    $projectId
                ]);
                
                header('Location: index.php?success=project_updated');
                exit();
                
            default:
                throw new Exception('Invalid action');
        }
        
    } catch (Exception $e) {
        header('Location: index.php?error=' . urlencode($e->getMessage()));
        exit();
    }
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    $action = $_GET['action'];
    
    try {
        switch ($action) {
            case 'delete_client':
                $clientId = (int)$_GET['id'];
                
                if (empty($clientId)) {
                    throw new Exception('Client ID is required');
                }
                
                $pdo->beginTransaction();
                
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$clientId]);
                
                $pdo->commit();
                
                header('Location: index.php?success=client_deleted');
                exit();
                
            case 'delete_project':
                $projectId = (int)$_GET['id'];
                
                if (empty($projectId)) {
                    throw new Exception('Project ID is required');
                }
                
                $stmt = $pdo->prepare("DELETE FROM projects WHERE id = ?");
                $stmt->execute([$projectId]);
                
                header('Location: index.php?success=project_deleted');
                exit();
                
            case 'delete_request':
                $requestId = (int)$_GET['id'];
                
                if (empty($requestId)) {
                    throw new Exception('Request ID is required');
                }
                
                $stmt = $pdo->prepare("DELETE FROM requests WHERE id = ?");
                $stmt->execute([$requestId]);
                
                header('Location: index.php?success=request_deleted');
                exit();
                
            case 'get_client_data':
                $clientId = (int)$_GET['id'];
                
                if (empty($clientId)) {
                    throw new Exception('Client ID is required');
                }
                
                $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$clientId]);
                $client = $stmt->fetch();
                
                if (!$client) {
                    throw new Exception('Client not found');
                }
                
                $projectsStmt = $pdo->prepare("SELECT * FROM projects WHERE user_id = ? ORDER BY created_at DESC");
                $projectsStmt->execute([$clientId]);
                $projects = $projectsStmt->fetchAll();
                
                $requestsStmt = $pdo->prepare("
                    SELECT r.*, p.project_name 
                    FROM requests r 
                    LEFT JOIN projects p ON r.project_id = p.id 
                    WHERE r.user_id = ? 
                    ORDER BY r.created_at DESC
                ");
                $requestsStmt->execute([$clientId]);
                $requests = $requestsStmt->fetchAll();
                
                header('Content-Type: application/json');
                echo json_encode([
                    'client' => $client,
                    'projects' => $projects,
                    'requests' => $requests
                ]);
                exit();
                
            case 'get_project_logs':
                $projectId = (int)$_GET['id'];
                
                if (empty($projectId)) {
                    throw new Exception('Project ID is required');
                }
                
                $stmt = $pdo->prepare("SELECT * FROM project_logs WHERE project_id = ? ORDER BY created_at DESC");
                $stmt->execute([$projectId]);
                $logs = $stmt->fetchAll();
                
                header('Content-Type: application/json');
                echo json_encode($logs);
                exit();
                
            case 'get_request_details':
                $requestId = (int)$_GET['id'];
                
                if (empty($requestId)) {
                    throw new Exception('Request ID is required');
                }
                
                $requestStmt = $pdo->prepare("
                    SELECT r.*, u.name as user_name, p.project_name 
                    FROM requests r 
                    JOIN users u ON r.user_id = u.id 
                    LEFT JOIN projects p ON r.project_id = p.id 
                    WHERE r.id = ?
                ");
                $requestStmt->execute([$requestId]);
                $request = $requestStmt->fetch();
                
                if (!$request) {
                    throw new Exception('Request not found');
                }
                
                $responsesStmt = $pdo->prepare("SELECT * FROM responses WHERE request_id = ? ORDER BY created_at ASC");
                $responsesStmt->execute([$requestId]);
                $responses = $responsesStmt->fetchAll();
                
                header('Content-Type: application/json');
                echo json_encode([
                    'request' => $request,
                    'responses' => $responses
                ]);
                exit();
                
            default:
                throw new Exception('Invalid action');
        }
        
    } catch (Exception $e) {
        if (isset($_GET['format']) && $_GET['format'] === 'json') {
            header('Content-Type: application/json');
            echo json_encode(['error' => $e->getMessage()]);
        } else {
            header('Location: index.php?error=' . urlencode($e->getMessage()));
        }
        exit();
    }
    
} else {
    header('Location: index.php');
    exit();
}
?>