<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");

include 'connection.php';
require 'vendor/autoload.php';

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;
use \Firebase\JWT\ExpiredException;

$secret_key = "1ED495A77B65435D317B3E6582E4C";

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');
} else {
    echo json_encode(["success" => false, "message" => "Authorization header missing"]);
    exit;
}

try {
    $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
    $company_id = $decoded->data->companyId;
    $uid = $decoded->data->uid;

    /* ==========================================================
       🚀 POST — INSERT NEW DEPOSIT + PROFILE IMAGE
    =========================================================== */
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        // multipart/form-data
        $deposit_no = $_POST['deposit_no'] ?? '';

        $name = trim($_POST['name'] ?? '');
        $mobile = trim($_POST['mobile'] ?? '');
        $pan = trim($_POST['pan_no'] ?? '');
        $deposit_date = trim($_POST['deposit_date'] ?? date('Y-m-d'));
        $exist_flag = $_POST['exist_flag'] ?? 0;
        $address = trim($_POST['address'] ?? null);
        $deposit_amt = $_POST['deposit_amt'] ?? 0;
        $interest_percent = $_POST['interest'] ?? 0;
        $deposit_type = trim($_POST['deposit_type'] ?? '');
        $deposit_mode = trim($_POST['deposit_mode'] ?? '');
        $cheque_no = trim($_POST['cheque_no'] ?? '');
        $bank_name = trim($_POST['bank_name'] ?? '');
        $interest_type = trim($_POST['interest_type'] ?? '');
        $cheque_date = trim($_POST['cheque_date'] ?? null);
        $int_amt = $_POST['int_amt'] ?? 0;
        $type = trim($_POST['type'] ?? '');
        $remarks = trim($_POST['remarks'] ?? '');

        /* ---------------------------------------
        ✅ Handle Profile Image Upload
        ----------------------------------------*/
        $profile_image_path = null;

        if (!empty($_FILES['profile_image']['name'])) {

            $upload_dir = "uploads/deposits/";
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $ext = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $newFileName = "DP_" . time() . "_" . rand(1000, 9999) . "." . $ext;

            $target_path = $upload_dir . $newFileName;

            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_path)) {
                $profile_image_path = $target_path;
            }
        }

        $stmt = $conn->prepare("INSERT INTO deposit_entry
            (deposit_no,com_id, name, mobile_no, pan_no, deposit_date, exist_flag, address,
             deposit_amt, interest_percent, deposit_type, ledger_name, cheque_no, 
             bank_name, interest_type, cheque_date, int_amt, type, remarks, profile_image) 
            VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $stmt->bind_param(
            "sissssisdsssssssisss",
            $deposit_no,
            $company_id,
            $name,
            $mobile,
            $pan,
            $deposit_date,
            $exist_flag,
            $address,
            $deposit_amt,
            $interest_percent,
            $deposit_type,
            $deposit_mode,
            $cheque_no,
            $bank_name,
            $interest_type,
            $cheque_date,
            $int_amt,
            $type,
            $remarks,
            $profile_image_path
        );

        if ($stmt->execute()) {
            $deposit_no = $deposit_no;

            $ledger = $deposit_mode;
            $particulars = $deposit_no . "-" . $name;

            $voucher_type = "Deposit";
            $credit = 0;
            $debit = $deposit_amt;
            $createdOn = date('Y-m-d H:i:s');

            $ledgerStmt = $conn->prepare("INSERT INTO ledger_day_wise 
                (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, credit, debit, createdOn) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $ledgerStmt->bind_param(
                "iisssssdds",
                $company_id,
                $uid,
                $deposit_date,
                $ledger,
                $particulars,
                $voucher_type,
                $deposit_no,
                $credit,
                $debit,
                $createdOn
            );
            $ledgerStmt->execute();
            $ledgerStmt->close();

            echo json_encode(["success" => true, "message" => "Deposit entry inserted successfully and ledger updated"]);
        } else {
            echo json_encode(["success" => false, "message" => "Insert failed: " . $stmt->error]);
        }

        $stmt->close();
    }

    /* ==========================================================
       🚀 GET — FETCH DEPOSITS
    =========================================================== */
    elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {

        // Check if we need to fetch deposit with payment entries
        $with_payments = isset($_GET['with_payments']) && $_GET['with_payments'] === 'true';
        $deposit_no = $_GET['deposit_no'] ?? '';

        if ($with_payments && !empty($deposit_no)) {
            // Fetch deposit with payment entries
            $stmt = $conn->prepare("SELECT * FROM deposit_entry WHERE com_id=? AND deposit_no=?");
            $stmt->bind_param("is", $company_id, $deposit_no);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                $stmt->close();
                echo json_encode(["success" => false, "message" => "Deposit not found"]);
                exit;
            }
            
            $deposit = $result->fetch_assoc();
            $stmt->close();

            // Fetch payment entries from deposit_entry table where type is 'payment_add' or 'payment_less'
            $payment_stmt = $conn->prepare("
                SELECT * FROM deposit_entry 
                WHERE com_id=? AND deposit_no=? AND type IN ('payment_add', 'payment_less')
                ORDER BY deposit_date DESC
            ");
            $payment_stmt->bind_param("is", $company_id, $deposit_no);
            $payment_stmt->execute();
            $payment_result = $payment_stmt->get_result();
            
            $payment_entries = [];
            while ($row = $payment_result->fetch_assoc()) {
                // Map type to add/less for display
                $row['payment_type_display'] = $row['type'] === 'payment_add' ? 'Add' : 'Less';
                $payment_entries[] = $row;
            }
            $payment_stmt->close();

            echo json_encode([
                "success" => true,
                "deposit" => $deposit,
                "payment_entries" => $payment_entries
            ]);
            exit;
        }

        // 1. Fetch deposits
        if (isset($_GET['deposit_no'])) {
            $deposit_no = $_GET['deposit_no'];

            $stmt = $conn->prepare("SELECT * FROM deposit_entry WHERE com_id=? AND deposit_no=?");
            $stmt->bind_param("is", $company_id, $deposit_no);

        } else {
            $stmt = $conn->prepare("SELECT * FROM deposit_entry WHERE com_id=?");
            $stmt->bind_param("i", $company_id);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        $deposits = [];
        while ($row = $result->fetch_assoc()) {
            // Check if this deposit has payment entries
            $payment_count_stmt = $conn->prepare("
                SELECT COUNT(*) as payment_count 
                FROM deposit_entry 
                WHERE com_id=? AND deposit_no=? AND type IN ('payment_add', 'payment_less')
            ");
            $payment_count_stmt->bind_param("is", $company_id, $row['deposit_no']);
            $payment_count_stmt->execute();
            $payment_count_result = $payment_count_stmt->get_result();
            $payment_count_row = $payment_count_result->fetch_assoc();
            $row['payment_count'] = intval($payment_count_row['payment_count'] ?? 0);
            $row['has_payments'] = $row['payment_count'] > 0;
            $payment_count_stmt->close();
            
            $deposits[] = $row;
        }
        $stmt->close();

        // 2. Fetch last deposit number
        $lastStmt = $conn->prepare("
            SELECT deposit_no 
            FROM deposit_entry 
            WHERE com_id=? 
            ORDER BY deposit_no DESC 
            LIMIT 1
        ");

        $lastStmt->bind_param("i", $company_id);
        $lastStmt->execute();
        $lastResult = $lastStmt->get_result();
        $lastRow = $lastResult->fetch_assoc();
        $lastStmt->close();

        // 3. Generate next deposit number
        if ($lastRow) {
            $last_deposit_no = $lastRow['deposit_no'];

            $prefix = substr($last_deposit_no, 0, 2);
            $year = substr($last_deposit_no, 2, 4);
            $number = intval(substr($last_deposit_no, 6));
            $next_number = $number + 1;

            $next_deposit_no = $prefix . $year . str_pad($next_number, 3, "0", STR_PAD_LEFT);

        } else {
            $prefix = "DP";
            $year = date("Y");
            $next_deposit_no = $prefix . $year . "001";
            $last_deposit_no = null;
        }

        echo json_encode([
            "success" => true,
            "last_deposit_no" => $last_deposit_no,
            "next_deposit_no" => $next_deposit_no,
            "data" => $deposits
        ]);
    }

    /* ==========================================================
 🚀 PUT — UPDATE DEPOSIT + PROFILE IMAGE  
=========================================================== */
elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {

    // Function to parse multipart/form-data for PUT requests
    function parseMultipartPut() {
        $putData = file_get_contents("php://input");

        $boundary = substr($putData, 0, strpos($putData, "\r\n"));
        if (empty($boundary)) {
            // Not multipart → parse normally
            parse_str($putData, $result);
            return $result;
        }

        $parts = array_slice(explode($boundary, $putData), 1);
        $data = array();

        foreach ($parts as $part) {
            if ($part == "--\r\n" || $part == "--") break;
            $part = ltrim($part, "\r\n");
            list($rawHeaders, $body) = explode("\r\n\r\n", $part, 2);

            $rawHeaders = explode("\r\n", $rawHeaders);
            $headers = array();
            foreach ($rawHeaders as $header) {
                list($name, $value) = explode(':', $header, 2);
                $headers[strtolower(trim($name))] = trim($value);
            }

            if (isset($headers['content-disposition'])) {
                $disposition = $headers['content-disposition'];
                preg_match('/name="([^"]+)"/', $disposition, $matches);

                if (isset($matches[1])) {
                    $fieldName = $matches[1];
                    $data[$fieldName] = substr($body, 0, strlen($body) - 2);
                }
            }
        }
        return $data;
    }

    // 🔥 NEW: Read raw input for JSON PUT
    $rawInput = file_get_contents("php://input");
    $jsonInput = json_decode($rawInput, true) ?? [];

    // Parse multipart PUT
    $parsedPut = parseMultipartPut();

    // Priority (corrected):
    // 1) GET query
    // 2) JSON
    // 3) multipart PUT
    // 4) $_POST fallback
    $deposit_no =
        ($_GET['deposit_no'] ?? '') ?:
        ($jsonInput['deposit_no'] ?? '') ?:
        ($parsedPut['deposit_no'] ?? '') ?:
        ($_POST['deposit_no'] ?? '');

    if (empty($deposit_no)) {
        echo json_encode([
            "success" => false,
            "message" => "Deposit No required",
            "debug" => [
                "get" => $_GET['deposit_no'] ?? null,
                "json" => $jsonInput['deposit_no'] ?? null,
                "parsed_put" => $parsedPut['deposit_no'] ?? null,
                "post" => $_POST['deposit_no'] ?? null,
                "content_type" => $_SERVER['CONTENT_TYPE'] ?? null
            ]
        ]);
        exit;
    }

    /* ---------------------------------------
       🔍 Fetch Old Image
    ----------------------------------------*/
    $imgStmt = $conn->prepare("SELECT profile_image FROM deposit_entry WHERE deposit_no=? AND com_id=?");
    $imgStmt->bind_param("si", $deposit_no, $company_id);
    $imgStmt->execute();
    $oldRow = $imgStmt->get_result()->fetch_assoc();
    $old_image_path = $oldRow['profile_image'] ?? null;
    $imgStmt->close();

    $profile_image_path = $old_image_path;

    /* ---------------------------------------
       📸 Update Image IF New File Uploaded
    ----------------------------------------*/
    if (!empty($_FILES['profile_image']['name'])) {
        $upload_dir = "uploads/deposits/";
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $ext = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
        $newFileName = "DP_" . time() . "_" . rand(1000, 9999) . "." . $ext;
        $target_path = $upload_dir . $newFileName;

        if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_path)) {
            $profile_image_path = $target_path;

            if (!empty($old_image_path) && file_exists($old_image_path)) {
                unlink($old_image_path);
            }
        }
    }

    // 🔥 Merge all PUT data sources
    $data = array_merge($jsonInput, $parsedPut, $_POST);

    // Extract all fields
    $name = $data['name'] ?? '';
    $mobile_no = $data['mobile_no'] ?? '';
    $pan_no = $data['pan_no'] ?? '';
    $deposit_date = $data['deposit_date'] ?? '';
    $exist_flag = $data['exist_flag'] ?? '0';
    $address = $data['address'] ?? '';
    $deposit_amt = $data['deposit_amt'] ?? '0';
    $interest_percent = $data['interest_percent'] ?? '0';
    $deposit_type = $data['deposit_type'] ?? '';
    $deposit_mode = $data['deposit_mode'] ?? '';
    $cheque_no = $data['cheque_no'] ?? '';
    $bank_name = $data['bank_name'] ?? '';
    $interest_type = $data['interest_type'] ?? '';
    $cheque_date = $data['cheque_date'] ?? '';
    $int_amt = $data['int_amt'] ?? '0';
    $type = $data['type'] ?? '';
    $remarks = $data['remarks'] ?? '';
    $ledger_name = $data['ledger_name'] ?? $deposit_mode;

    $stmt = $conn->prepare("UPDATE deposit_entry 
        SET name=?, mobile_no=?, pan_no=?, deposit_date=?, exist_flag=?, address=?, 
            deposit_amt=?, interest_percent=?, deposit_type=?, ledger_name=?, cheque_no=?, 
            bank_name=?, interest_type=?, cheque_date=?, int_amt=?, type=?, remarks=?, 
            profile_image=? 
        WHERE deposit_no=? AND com_id=?");

    $stmt->bind_param(
        "ssssisdsssssssissssi",
        $name, $mobile_no, $pan_no, $deposit_date, $exist_flag, $address,
        $deposit_amt, $interest_percent, $deposit_type, $deposit_mode,
        $cheque_no, $bank_name, $interest_type, $cheque_date,
        $int_amt, $type, $remarks, $profile_image_path,
        $deposit_no, $company_id
    );

    if ($stmt->execute()) {
        $particulars = $deposit_no . "-" . $name;
        $zero = 0;

        $ledgerUpdate = $conn->prepare(
            "UPDATE ledger_day_wise 
             SET date=?, ledger=?, particulars=?, voucher_type=?, voucher_number=?, credit=?, debit=? 
             WHERE com_id=? AND particulars = ?"
        );

        $ledgerUpdate->bind_param(
            "sssssdiis",
            $deposit_date, $ledger_name, $particulars,
            $deposit_mode, $deposit_no, $zero, $deposit_amt,
            $company_id, $particulars
        );

        $ledgerUpdate->execute();
        $ledgerUpdate->close();

        echo json_encode(["success" => true, "message" => "Deposit and ledger updated successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Update failed: " . $stmt->error]);
    }

    $stmt->close();
}


    /* ==========================================================
       🚀 DELETE — REMOVE DEPOSIT + LEDGER
    =========================================================== */
   elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $data = json_decode(file_get_contents("php://input"), true);
    $deposit_no = $data['deposit_no'] ?? '';

    if (empty($deposit_no)) {
        echo json_encode(["success" => false, "message" => "Deposit No required"]);
        exit;
    }

    $stmt = $conn->prepare("DELETE FROM deposit_entry WHERE deposit_no=? AND com_id=?");
    $stmt->bind_param("si", $deposit_no, $company_id);

    if ($stmt->execute()) {
        $ledgerDel = $conn->prepare(
            "DELETE FROM ledger_day_wise WHERE com_id=? AND voucher_number=?"
        );
        $ledgerDel->bind_param("is", $company_id, $deposit_no);
        $ledgerDel->execute();
        $ledgerDel->close();

        echo json_encode(["success" => true, "message" => "Deposit and ledger deleted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Delete failed: " . $stmt->error]);
    }

    $stmt->close();
}

    else {
        echo json_encode(["success" => false, "message" => "Invalid request method"]);
    }

} catch (ExpiredException $e) {
    echo json_encode(["success" => false, "message" => "Token expired"]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Token invalid", "error" => $e->getMessage()]);
}

$conn->close();
?>

