<?php
// update_bondhoki.php
require 'db.php';

// Ensure POST method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: bondhoki.php');
    exit;
}

// Required fields
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
$amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0.0;
$percent = isset($_POST['percent']) ? (float)$_POST['percent'] : 0.0;
$months = isset($_POST['months']) ? (int)$_POST['months'] : 0;

// Basic validation
if ($id <= 0 || $name === '' || $phone === '' || $item_name === '') {
    // Bad request — redirect back with error
    header('Location: bondhoki.php?error=missing');
    exit;
}

// Handle image upload if provided
$uploadedImagePath = null;
if (!empty($_FILES['image']) && $_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE) {
    $img = $_FILES['image'];
    // check upload errors
    if ($img['error'] === UPLOAD_ERR_OK) {
        // Validate file extension (allow jpg, jpeg, png, webp)
        $allowed = ['jpg','jpeg','png','webp'];
        $ext = strtolower(pathinfo($img['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            // invalid file type
            header('Location: bondhoki.php?error=bad_image_type');
            exit;
        }

        // create uploads dir if not exists
        $uploadDir = __DIR__ . '/uploads/bondhoki_images';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        // generate unique filename
        $basename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', pathinfo($img['name'], PATHINFO_FILENAME));
        $newName = $basename . '_' . time() . '.' . $ext;
        $destPath = $uploadDir . '/' . $newName;

        if (move_uploaded_file($img['tmp_name'], $destPath)) {
            // store relative path for DB (match how you store currently)
            $uploadedImagePath = 'uploads/bondhoki_images/' . $newName;
        } else {
            header('Location: bondhoki.php?error=upload_fail');
            exit;
        }
    } else {
        header('Location: bondhoki.php?error=upload_error');
        exit;
    }
}

// Build SQL: update customer only. DO NOT touch bondhoki_payments here.
if ($uploadedImagePath !== null) {
    $sql = "UPDATE bondhoki_customers 
            SET name = ?, phone = ?, item_name = ?, amount = ?, percent = ?, months = ?, image = ?
            WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        header('Location: bondhoki.php?error=db');
        exit;
    }
    $stmt->bind_param('sssddisi', $name, $phone, $item_name, $amount, $percent, $months, $uploadedImagePath, $id);
} else {
    $sql = "UPDATE bondhoki_customers 
            SET name = ?, phone = ?, item_name = ?, amount = ?, percent = ?, months = ?
            WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        header('Location: bondhoki.php?error=db');
        exit;
    }
    $stmt->bind_param('sssddii', $name, $phone, $item_name, $amount, $percent, $months, $id);
}

$ok = $stmt->execute();
if ($ok) {
    // Success: IMPORTANT — do NOT modify bondhoki_payments here.
    // If you want to regenerate schedule, do it from a separate endpoint after confirming user intent.
    header('Location: bondhoki.php?updated=1');
    exit;
} else {
    error_log("Update failed: " . $stmt->error);
    header('Location: bondhoki.php?error=update_fail');
    exit;
}
?>
