<?php
// FINAL SCRIPT: update_offer.php

// --- 1. Prevent Network Errors & Set Up ---
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php'; 

header('Content-Type: application/json');

ob_clean();

$response = [];

// --- 2. Validation ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection is not available.';
    echo json_encode($response);
    exit;
}

// Check for the offer ID, which is essential for an update
if (!isset($_POST['id']) || empty($_POST['id'])) {
    http_response_code(400); 
    $response['status'] = 'error';
    $response['message'] = 'Offer ID is missing.';
    echo json_encode($response);
    exit;
}

// Check other required fields
$required_fields = ['title', 'description', 'start_date', 'end_date', 'image_path'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field])) {
        http_response_code(400);
        $response['status'] = 'error';
        $response['message'] = "Required field '{$field}' is missing.";
        echo json_encode($response);
        exit;
    }
}

// --- 3. Assign and Sanitize Data ---
$offer_id    = intval($_POST['id']);
$title       = trim($_POST['title']);
$description = trim($_POST['description']);
$start_date  = trim($_POST['start_date']);
$end_date    = trim($_POST['end_date']);
$image_path  = trim($_POST['image_path']);

// --- 4. Prepare and Execute the Database UPDATE ---
$sql = "UPDATE offers SET 
            title = ?, 
            description = ?, 
            start_date = ?, 
            end_date = ?, 
            image_url = ? 
        WHERE 
            id = ?";

$stmt = $conn->prepare($sql);

if ($stmt) {
    // Bind parameters to the SQL query
    // s = string, i = integer
    $stmt->bind_param("sssssi", $title, $description, $start_date, $end_date, $image_path, $offer_id);
    
    if ($stmt->execute()) {
        // --- Success ---
        $response['status'] = 'success';
        $response['message'] = 'Offer updated successfully.';
    } else {
        // --- Failure (Database Execute) ---
        http_response_code(500);
        $response['status'] = 'error';
        $response['message'] = 'Database Error: Could not execute the update. ' . $stmt->error;
    }
    $stmt->close();
} else {
    // --- Failure (Database Prepare) ---
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database Error: Could not prepare the statement. ' . $conn->error;
}

// --- 5. Final Clean Output ---
echo json_encode($response);

$conn->close();
exit;
?>