<?php
session_start();

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

error_reporting(0);  ini_set('display_errors', 0);

require_once '../includes/db_config.php';

    // يتحقق من صلاحيات ان كان الشخص ادمن او لا
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit;
}

try {
       
    $db = getDBConnection();
    
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (isset($_GET['id'])) {
            $sid = $_GET['id'];
            $st1 = $db->prepare("SELECT * FROM services WHERE id = ?");
            $st1->execute([$sid]);
            $svc = $st1->fetch();
            
            if ($svc) {
                echo json_encode(['success' => true, 'data' => $svc]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Service not found']);
            }
        } else {
            $st2 = $db->prepare("SELECT * FROM services ORDER BY created_at DESC");
            $st2->execute();
            $rows = $st2->fetchAll();
            echo json_encode(['success' => true, 'data' => $rows]);
        }
    }
    
   
    elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $nm = $_POST['name'] ?? '';
        $desc = $_POST['description'] ?? '';
        $pr = $_POST['price'] ?? 0;   
        $cat = $_POST['category'] ?? 'basic';
        $id = $_POST['id'] ?? null;
        
        if (empty($nm) || empty($pr)) { echo json_encode(['success'=>false,'error'=>'Name and price are required']); exit; }
        
        
        $img = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $ok = ['image/jpeg','image/png','image/gif','image/webp'];
            $max = 2 * 1024 * 1024; // حد حجم الصوره 2mb
            if (!in_array($_FILES['image']['type'], $ok)) { echo json_encode(['success'=>false,'error'=>'Invalid image type. Only JPG, PNG, GIF, and WEBP are allowed']); exit; }
            if ($_FILES['image']['size'] > $max) { echo json_encode(['success'=>false,'error'=>'Image size must be less than 2MB']); exit; }

            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $img = 'service_' . time() . '_' . uniqid() . '.' . $ext;
            $path = '../img/' . $img;
            if (!move_uploaded_file($_FILES['image']['tmp_name'], $path)) { echo json_encode(['success'=>false,'error'=>'Failed to upload image']); exit; }
        }
        
        if ($id) {
        
            if ($img) {
                $st3 = $db->prepare("SELECT image FROM services WHERE id = ?");
                $st3->execute([$id]);
                $old = $st3->fetch();
                if ($old && $old['image'] && file_exists('../img/' . $old['image'])) { unlink('../img/' . $old['image']); }

                $st4 = $db->prepare("UPDATE services SET name = ?, description = ?, price = ?, category = ?, image = ? WHERE id = ?");
                $st4->execute([$nm, $desc, $pr, $cat, $img, $id]);
            } else {
                $st5 = $db->prepare("UPDATE services SET name = ?, description = ?, price = ?, category = ? WHERE id = ?");
                $st5->execute([$nm, $desc, $pr, $cat, $id]);
            }
            echo json_encode(['success'=>true,'message'=>'Service updated successfully']);
        } else {
        
            $st6 = $db->prepare("INSERT INTO services (name, description, price, category, image) VALUES (?, ?, ?, ?, ?)");
            $st6->execute([$nm, $desc, $pr, $cat, $img]);
            echo json_encode(['success'=>true,'message'=>'Service added successfully','id'=>$db->lastInsertId()]);
        }
    }
    
  
    elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        $input = json_decode(file_get_contents('php://input'), true);
        $id = $input['id'] ?? null;
        if (!$id) { echo json_encode(['success'=>false,'error'=>'Service ID is required']); exit; }

        $st7 = $db->prepare("SELECT image FROM services WHERE id = ?");
        $st7->execute([$id]);
        $svc = $st7->fetch();

        $st8 = $db->prepare("DELETE FROM services WHERE id = ?");
        $st8->execute([$id]);

        if ($svc && $svc['image'] && file_exists('../img/' . $svc['image'])) { unlink('../img/' . $svc['image']); }

        echo json_encode(['success'=>true,'message'=>'Service deleted successfully']);
    }
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Error: ' . $e->getMessage()]);
}
?>
