#!/bin/bash

#==============================================================================
# RASHWAN'S BARBER POS - QUICK INSTALLATION SCRIPT
#==============================================================================
# This script installs:
# 1. CashUp Model
# 2. Cash-Up View Files
# 3. Updated Transaction Model (with methods needed for cash-up)
# 4. Updated Report Controller
# 5. Report View Files
#
# Usage: sudo bash QUICK_INSTALL.sh
#==============================================================================

set -e  # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Base directory
BASE_DIR="/var/www/html/barber"

echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}RASHWAN'S BARBER POS - INSTALLATION${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}This script must be run as root (use sudo)${NC}" 
   exit 1
fi

# Check if base directory exists
if [ ! -d "$BASE_DIR" ]; then
    echo -e "${RED}Error: $BASE_DIR does not exist${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Running as root${NC}"
echo -e "${GREEN}✓ Base directory found${NC}"
echo ""

#==============================================================================
# STEP 1: Install CashUp Model
#==============================================================================
echo -e "${YELLOW}[1/5] Installing CashUp Model...${NC}"

cat > "$BASE_DIR/app/models/CashUp.php" << 'EOF'
<?php
/**
 * CashUp Model - See artifact for full code
 * This is a placeholder - you need to copy the full code from the CashUp.php artifact
 */
class CashUp {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    // All methods from the artifact should be here
    // Copy from the cashup-model artifact I created
}
EOF

echo -e "${GREEN}✓ CashUp Model created (needs full code from artifact)${NC}"

#==============================================================================
# STEP 2: Create Cash-Up Views Directory
#==============================================================================
echo -e "${YELLOW}[2/5] Creating Cash-Up views directory...${NC}"

mkdir -p "$BASE_DIR/app/views/cashup"

echo -e "${GREEN}✓ Cash-Up views directory created${NC}"

#==============================================================================
# STEP 3: Add Transaction Model Methods
#==============================================================================
echo -e "${YELLOW}[3/5] Checking Transaction Model...${NC}"

if [ -f "$BASE_DIR/app/models/Transaction.php" ]; then
    echo -e "${GREEN}✓ Transaction Model exists${NC}"
    echo -e "${YELLOW}  Note: You may need to add getDailyTotals() and getPaymentBreakdown() methods${NC}"
else
    echo -e "${RED}✗ Transaction Model not found${NC}"
    echo -e "${YELLOW}  Creating basic Transaction Model...${NC}"
    
    cat > "$BASE_DIR/app/models/Transaction.php" << 'EOF'
<?php
class Transaction {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    /**
     * Get daily totals for cash-up
     */
    public function getDailyTotals($locationId, $date) {
        try {
            $query = "SELECT 
                        COUNT(DISTINCT t.transaction_id) as transaction_count,
                        SUM(t.total_amount) as total_sales,
                        SUM(t.subtotal) as subtotal,
                        SUM(t.vat_amount) as vat_amount,
                        COUNT(DISTINCT CASE WHEN p.payment_method = 'cash' THEN t.transaction_id END) as cash_count,
                        COUNT(DISTINCT CASE WHEN p.payment_method = 'card' THEN t.transaction_id END) as card_count,
                        COUNT(DISTINCT CASE WHEN p.payment_method = 'mobile_payment' THEN t.transaction_id END) as mobile_count
                      FROM transactions t
                      LEFT JOIN payments p ON t.transaction_id = p.transaction_id
                      WHERE t.location_id = :location_id
                      AND DATE(t.transaction_date) = :date
                      AND t.status = 'completed'";
            
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':location_id', $locationId);
            $stmt->bindParam(':date', $date);
            $stmt->execute();
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (PDOException $e) {
            error_log("Transaction getDailyTotals Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get payment method breakdown for cash-up
     */
    public function getPaymentBreakdown($locationId, $date) {
        try {
            $query = "SELECT 
                        SUM(CASE WHEN p.payment_method = 'cash' THEN p.amount ELSE 0 END) as cash,
                        SUM(CASE WHEN p.payment_method = 'card' THEN p.amount ELSE 0 END) as card,
                        SUM(CASE WHEN p.payment_method = 'mobile_payment' THEN p.amount ELSE 0 END) as mobile_payment
                      FROM payments p
                      INNER JOIN transactions t ON p.transaction_id = t.transaction_id
                      WHERE t.location_id = :location_id
                      AND DATE(t.transaction_date) = :date
                      AND t.status = 'completed'";
            
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':location_id', $locationId);
            $stmt->bindParam(':date', $date);
            $stmt->execute();
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (PDOException $e) {
            error_log("Transaction getPaymentBreakdown Error: " . $e->getMessage());
            return false;
        }
    }
}
EOF

    echo -e "${GREEN}✓ Basic Transaction Model created${NC}"
fi

#==============================================================================
# STEP 4: Create Reports Directory
#==============================================================================
echo -e "${YELLOW}[4/5] Checking Reports directory...${NC}"

if [ -d "$BASE_DIR/app/views/reports" ]; then
    echo -e "${GREEN}✓ Reports directory exists${NC}"
else
    mkdir -p "$BASE_DIR/app/views/reports"
    echo -e "${GREEN}✓ Reports directory created${NC}"
fi

#==============================================================================
# STEP 5: Set Permissions
#==============================================================================
echo -e "${YELLOW}[5/5] Setting permissions...${NC}"

chown -R apache:apache "$BASE_DIR"
chmod -R 755 "$BASE_DIR"
chmod -R 775 "$BASE_DIR/storage"

echo -e "${GREEN}✓ Permissions set${NC}"

#==============================================================================
# COMPLETION
#==============================================================================
echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${GREEN}INSTALLATION COMPLETE!${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
echo -e "${YELLOW}NEXT STEPS:${NC}"
echo ""
echo -e "1. Copy full CashUp.php code from artifact to:"
echo -e "   ${BLUE}$BASE_DIR/app/models/CashUp.php${NC}"
echo ""
echo -e "2. Install TCPDF for PDF reports:"
echo -e "   ${BLUE}cd $BASE_DIR && composer require tecnickcom/tcpdf${NC}"
echo ""
echo -e "3. Restart Apache:"
echo -e "   ${BLUE}systemctl restart httpd${NC}"
echo ""
echo -e "4. Test Cash-Up by:"
echo -e "   - Making a transaction in POS"
echo -e "   - Going to Cash-Up menu"
echo -e "   - Creating end-of-day cash-up"
echo ""
echo -e "${GREEN}Installation script completed!${NC}"
echo ""
