<?php
require 'header.php';
require 'db.php'; // $conn (mysqli)

// Basic validation
$name = trim($_POST['name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$item_name = trim($_POST['item_name'] ?? '');
$amount = floatval($_POST['amount'] ?? 0);
$percent = floatval($_POST['percent'] ?? 0);
$months = intval($_POST['months'] ?? 12);
$start_date = $_POST['start_date'] ?? date('Y-m-d');

if($name === '' || $amount <= 0 || $months <= 0) {
    die('Invalid input. Go back and provide valid data.');
}

// handle upload (optional)
$imagePath = null;
if(isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK){
    $uploaddir = 'uploads/bondhoki_images';
    if(!is_dir($uploaddir)) mkdir($uploaddir, 0755, true);
    $tmp = $_FILES['image']['tmp_name'];
    $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $filename = time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
    $dest = $uploaddir . '/' . $filename;
    if(move_uploaded_file($tmp, $dest)){
        $imagePath = $dest;
    }
}

// insert into bondhoki_customers
$stmt = $conn->prepare("INSERT INTO bondhoki_customers (name, phone, item_name, image, amount, percent, months, start_date) VALUES (?,?,?,?,?,?,?,?)");
$stmt->bind_param('ssssddis', $name, $phone, $item_name, $imagePath, $amount, $percent, $months, $start_date);
if(!$stmt->execute()){
    die('DB insert error: ' . $stmt->error);
}
$bondhoki_id = $stmt->insert_id;
$stmt->close();

// compute monthly due amount (interest per month)
// monthly interest = amount * percent / 100 / 12
$monthly_due = round($amount * ($percent / 100) / 12, 2);

// create payment rows for each month
$ins = $conn->prepare("INSERT INTO bondhoki_payments (bondhoki_id, month_no, due_amount) VALUES (?,?,?)");
for($m=1;$m<=$months;$m++){
    $ins->bind_param('iid', $bondhoki_id, $m, $monthly_due);
    $ins->execute();
}
$ins->close();

// redirect to list
header('Location: bondhoki_list.php');
exit;
