<?php
include '../config.php';
date_default_timezone_set('Africa/Dar_es_Salaam');

// Check if all required fields are set
$required_fields = ['branch_id', 'firstname', 'middlename', 'lastname', 'phone', 'country', 'region', 'gps', 'street', 'ward', 'nation_id'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        echo json_encode(["error" => "$field is required"]);
        exit;
    }
}

$branch_id = intval($_POST['branch_id']);
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$region = $_POST['region'];
$gps = $_POST['gps'];
$street = $_POST['street'];
$ward = $_POST['ward'];
$nation_id = $_POST['nation_id'];
$created_at = date("Y-m-d H:i:s");

// Kwanza, angalia kama simu tayari imetumika
$sql_check = "SELECT id FROM customers WHERE phone = ?";
if($stmt_check = $conn->prepare($sql_check)){
    $stmt_check->bind_param("s", $phone);
    $stmt_check->execute();
    $stmt_check->store_result();
    if($stmt_check->num_rows > 0){
        echo json_encode(["error" => "This phone number has already been used for registration."]);
        $stmt_check->close();
        $conn->close();
        exit;
    }
    $stmt_check->close();
} else {
    echo json_encode(["error" => "Failed to prepare statement for phone check."]);
    $conn->close();
    exit;
}


// Process image if available
$image_path = "";
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){
    $target_dir = "../uploads/customers/";
    if(!is_dir($target_dir)){
        mkdir($target_dir, 0755, true);
    }
    $imageFileType = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $new_filename = uniqid() . "." . $imageFileType;
    $target_file = $target_dir . $new_filename;
    if(move_uploaded_file($_FILES['image']['tmp_name'], $target_file)){
        // Save full path in the database
        $image_path = $target_file;
    } else {
        echo json_encode(["error" => "Failed to upload image"]);
        exit;
    }
}

// Insert data into the database (make sure your table has columns for all fields including nation_id and image)
$sql = "INSERT INTO customers (branch_id, firstname, middlename, lastname, phone, country, region, gps, street, ward, nation_id, image, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if($stmt = $conn->prepare($sql)){
    $stmt->bind_param("issssssssssss", $branch_id, $firstname, $middlename, $lastname, $phone, $country, $region, $gps, $street, $ward, $nation_id, $image_path, $created_at);
    if($stmt->execute()){
        echo json_encode(["success" => true, "message" => "Customer registered successfully"]);
    } else {
        echo json_encode(["error" => "Failed to register customer"]);
    }
    $stmt->close();
} else {
    echo json_encode(["error" => "Failed to prepare statement"]);
}
$conn->close();
?>
