<?php
session_start();
require 'config/db.php';

if(!isset($_SESSION['manager_id'])) die('Unauthorized');

$sales_id = $_SESSION['manager_id'];
$sales_name = $_SESSION['full_name'] ?? 'Sales';

/* ===============================
   RECEIVE REMAINING PAYMENT + COMPLETE
================================ */
if(isset($_POST['complete_project'])){
    $project_id = (int)$_POST['project_id'];
    $receive    = (float)$_POST['receive_amount'];
    $tip        = (float)$_POST['tip_amount'];

    // Fetch project
    $stmt = $pdo->prepare("
        SELECT payment_received, payment_remaining, status
        FROM projects
        WHERE id=? AND sales_id=?
    ");
    $stmt->execute([$project_id,$sales_id]);
    $project = $stmt->fetch();

    if(!$project) die('Invalid project');
    if($project['status'] === 'Completed') die('Project already completed');
    if($receive > $project['payment_remaining']) die('Received amount cannot exceed remaining payment');

    // Auto calculation
    $new_received  = $project['payment_received'] + $receive;
    $new_remaining = $project['payment_remaining'] - $receive;

    // Update project
    $pdo->prepare("
        UPDATE projects
        SET payment_received=?, payment_remaining=?, tip_amount=?, status='Completed'
        WHERE id=? AND sales_id=?
    ")->execute([$new_received,$new_remaining,$tip,$project_id,$sales_id]);

    // Payment Screenshot
    if(!empty($_FILES['payment_file']['name'])){
        $file = 'pay_'.time().'_'.$_FILES['payment_file']['name'];
        move_uploaded_file($_FILES['payment_file']['tmp_name'], "../../employees/uploads/payments/".$file);

        $pdo->prepare("
            INSERT INTO project_files
            (project_id, uploaded_by, file_stage, file_path)
            VALUES (?,?,?,?)
        ")->execute([$project_id,'Sales','Payment',$file]);
    }

    // Action log
    $pdo->prepare("
        INSERT INTO project_actions
        (project_id, action_by, action)
        VALUES (?,?,?)
    ")->execute([$project_id,'Sales','Completed']);

    $success = "Project completed and payment updated successfully.";
}

/* ===============================
   FETCH READY PROJECTS
================================ */
$stmt = $pdo->prepare("
    SELECT * FROM projects
    WHERE sales_id=? AND status='FinalFilesUploaded'
    ORDER BY created_at DESC
");
$stmt->execute([$sales_id]);
$projects = $stmt->fetchAll();

/* ===== PAGE TITLE ===== */
$page_title = "Sales Manager • Final Payment & Completion";

/* ===== LAYOUT START ===== */
include 'assets/layout_top.php';
?>

<div class="glass-panel">

<h3 class="mb-4 text-center">Final Review, Payment & Completion</h3>

<?php if(isset($success)): ?>
<div class="alert alert-success text-center"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<?php if(!$projects): ?>
<div class="glass-card text-center">
<i class="fa-solid fa-circle-info fa-2x mb-2"></i>
<p class="mb-0">No projects waiting for completion</p>
</div>
<?php endif; ?>

<?php foreach($projects as $p): ?>
<div class="glass-card mb-4 p-3">

<h5 class="mb-3">
<i class="fa-solid fa-folder-open me-2"></i>
<?= htmlspecialchars($p['title']) ?>
<span class="badge bg-success ms-2">Final Approved</span>
</h5>

<p><i class="fa-solid fa-user me-1"></i> <b>Client:</b> <?= htmlspecialchars($p['client_name']) ?></p>
<p><i class="fa-solid fa-money-bill-wave me-1"></i> <b>Total Price:</b> $<?= number_format($p['price'],2) ?></p>
<p><i class="fa-solid fa-receipt me-1"></i> <b>Received:</b> $<?= number_format($p['payment_received'],2) ?></p>
<p><i class="fa-solid fa-hourglass-half me-1"></i> <b>Remaining:</b> 
<span class="badge bg-warning text-dark">$<?= number_format($p['payment_remaining'],2) ?></span>
</p>

<hr>

<h6><i class="fa-solid fa-paperclip me-1"></i> Final Files</h6>
<?php
$files = $pdo->prepare("SELECT * FROM project_files WHERE project_id=? AND file_stage='Final'");
$files->execute([$p['id']]);
foreach($files as $f):
?>
<div class="file-box mb-1">
<a href="../../employees/uploads/finals/<?= htmlspecialchars($f['file_path']) ?>" target="_blank">
<i class="fa-solid fa-file-lines me-1"></i>
<?= htmlspecialchars($f['file_path']) ?>
</a>
</div>
<?php endforeach; ?>

<hr>

<form method="POST" enctype="multipart/form-data" class="row g-2">
<input type="hidden" name="project_id" value="<?= $p['id'] ?>">

<div class="col-md-4">
<label>Receive Remaining Payment</label>
<input type="number" step="0.01" name="receive_amount"
       max="<?= $p['payment_remaining'] ?>"
       class="form-control" required>
</div>

<div class="col-md-4">
<label>Tip Amount</label>
<input type="number" step="0.01" name="tip_amount"
       class="form-control" value="0">
</div>

<div class="col-md-4">
<label>Payment Screenshot</label>
<input type="file" name="payment_file" class="form-control" required>
</div>

<div class="col-md-12 mt-2">
<button name="complete_project" class="btn-main w-100">
<i class="fa-solid fa-check me-1"></i> Receive Payment & Complete Project
</button>
</div>
</form>

</div>
<?php endforeach; ?>

</div>

<?php
/* ===== LAYOUT END ===== */
include 'assets/layout_bottom.php';
?>
